package service

import (
	"context"
	"fmt"
	"iris-wms/apps/admin/web/dto/dout"
	"iris-wms/common/model"
	"iris-wms/common/pkg/db"
	"iris-wms/common/pkg/db/dao"
)

var _ WmsWarehouseService = (*wmsWarehouseService)(nil)

type WmsWarehouseService interface {
	Create(model.WmsWarehouse) error
	Update(model.WmsWarehouse) error
	DeleteByIdList([]uint) error
	GetList(string) ([]*dout.WmsWarehouseOut, error)
	GetAreaList(uint) ([]*dout.WmsWarehouseOut, error)
}

func NewWmsWarehouseService() *wmsWarehouseService {
	return &wmsWarehouseService{}
}

type wmsWarehouseService struct{}

func (impl *wmsWarehouseService) Create(in model.WmsWarehouse) (err error) {
	err = db.GDB1.Create(&in).Error
	return
}

func (impl *wmsWarehouseService) Update(in model.WmsWarehouse) (err error) {
	err = db.GDB1.Save(&in).Error
	return
}

func (impl *wmsWarehouseService) DeleteByIdList(idList []uint) (err error) {
	err = db.GDB1.Delete(&model.WmsWarehouse{}, "id in ?", idList).Error
	return err
}

func (impl *wmsWarehouseService) GetList(word string) (rows []*dout.WmsWarehouseOut, err error) {
	q := dao.Use(db.GDB1).WmsWarehouseOut
	do := q.WithContext(context.Background())

	if word != "" {
		word := fmt.Sprintf("%%%s%%", word)
		do = do.Where(do.Where(q.Code.Like(word)).Or(q.Name.Like(word)))
	}
	rows, err = do.
		Where(q.ParentId.Eq(0)).
		Preload(q.AreaList).
		Find()
	return
}

func (impl *wmsWarehouseService) GetAreaList(wid uint) (rows []*dout.WmsWarehouseOut, err error) {
	q := dao.Use(db.GDB1).WmsWarehouseOut
	rows, err = q.WithContext(context.Background()).
		Where(q.ParentId.Eq(wid)).
		Preload(q.AreaList).Find()
	return
}
